package cn.vihub.service.impl;

import cn.vihub.handler.MyRuntimeException;
import cn.vihub.param.ShopUserParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.vihub.pojo.ShopUserToRole;
import cn.vihub.service.ShopUserToRoleService;
import cn.vihub.mapper.ShopUserToRoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author 64452
* @description 针对表【shop_user_to_role(用户角色关联表)】的数据库操作Service实现
* @createDate 2025-07-17 20:43:24
*/
@Service
public class ShopUserToRoleServiceImpl extends ServiceImpl<ShopUserToRoleMapper, ShopUserToRole>
    implements ShopUserToRoleService{

    @Override
    @Transactional
    public Boolean binRole(ShopUserParam shopUserParam) {

        // 删除之前的数据
        LambdaQueryWrapper<ShopUserToRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShopUserToRole::getUserId, shopUserParam.getId());
        remove(lambdaQueryWrapper);


        // 用户id
        Integer userId = shopUserParam.getId();

        // 多个角色id的list
        List<Integer> roleIdList = shopUserParam.getRoleIdList();

        // 构造一个list 用来存储要关联的数据
        ArrayList<ShopUserToRole> list = new ArrayList<>();
        for (Integer roleId : roleIdList){
            ShopUserToRole shopUserToRole = new ShopUserToRole();
            shopUserToRole.setUserId(userId);
            shopUserToRole.setRoleId(roleId);
            // 加到list中
            list.add(shopUserToRole);
        }

        return saveBatch(list);
    }

    /**
     * 通过userid获取关联的角色id
     * @param
     * @return
     */
    @Override
    public List<ShopUserToRole> listByUserId(Integer userId) {

        LambdaQueryWrapper<ShopUserToRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShopUserToRole::getUserId, userId);

        return list(lambdaQueryWrapper);
    }

    @Override
    public void isUserByRoleId(Integer id) {

        LambdaQueryWrapper<ShopUserToRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShopUserToRole::getRoleId, id);
        int count = count(lambdaQueryWrapper);

        if (count > 0){
            throw new MyRuntimeException("角色下存在用户，不能删除");
        }
    }
}




